//
//  ZZFNetWorkCore.m
//  zhangzhongfo
//
//  Created by 瞿衡 on 17/1/13.
//  Copyright © 2017年 瞿衡. All rights reserved.
//

#import "BZUCLoginService.h"
#import <BZPreHeaderComponent/BZPreHeaderComponent.h>
#import <AFNetworking/AFNetworking.h>
#import <BZDataBaseSDK/BZDataBaseSDK.h>
#import "BZUCUserModel.h"
#import <YYKit/NSString+YYAdd.h>
#import "BZUCCurrentUser.h"
#import <BZPreHeaderComponent/BZPreHeaderComponent.h>
#import <BZBaseNetWorkSDK/BZBaseNetWorkSDK.h>
#import "BZDbUserTable.h"

#import <BZUCSDK/BZUCUser.h>
#import <BZUCSDK/BZUCDataBaseManager.h>


@interface BZUCLoginService()

@property (nonatomic, strong) BZBaseRequestModel *requestModel;

@property (nonatomic, strong) BZBaseRequest      *baseRequest;

@property (nonatomic, strong) BZDbUserTable      *userTable;

@end


@implementation BZUCLoginService


- (BZBaseRequestModel *)requestModel{

    if (!_requestModel) {
        _requestModel = [[BZBaseRequestModel alloc]init];
    }
    return _requestModel;
}

- (BZBaseRequest *)baseRequest{

    if (!_baseRequest) {
        _baseRequest = [[BZBaseRequest alloc]init];
    }
    return _baseRequest;
}


- (void)fetchRequestWithParam:(NSDictionary *)param
                   requestUri:(NSString *)requestUri
                   httpMethod:(BZRequestType)requestType
                 hasSessionId:(BOOL)hasSessionId
                      success:(void(^)(NSString *code , id responseObject))success
                      failure:(void(^)(NSString *code,NSError *error))failure{

    self.requestModel.param       = param;
    self.requestModel.requestUri  = requestUri;
    self.requestModel.requestType = requestType;
    
    [self.baseRequest requestByModelAsync:self.requestModel success:success failure:failure];
    
}


- (void)getSMSCodeByPhoneNumber:(NSString *)phoneNum
                       withImei:(NSString*)imei
                       withCode:(NSInteger) type
                        success:(void(^)(NSString *code , id responseObject))success
                        failure:(void(^)(NSString *code,NSError *error))failure{
    
    
    if ([phoneNum length]) {
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];  //@{@"phone":phoneNum};
        
        param[@"phone"]         = phoneNum;
        param[@"imei"]          = imei;
        param[@"code"]          = @(type);
        self.requestModel.param = param;
        
        [self fetchRequestWithParam:param
                         requestUri:@"api/register/phone-code"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];

    }    
}


- (void)checkCodeByParam:(NSDictionary *)param
                 success:(void(^)(NSString *code , id responseObject))success
                 failure:(void(^)(NSString *code,NSError *error))failure{

    [self fetchRequestWithParam:param
                     requestUri:@"api/register/check-code"
                     httpMethod:BZPostRequest
                   hasSessionId:NO
                        success:success
                        failure:failure];


}



- (void)registerUserByParam:(NSDictionary *)param
                    success:(void(^)(NSString *code , id responseObject))success
                    failure:(void(^)(NSString *code,NSError *error))failure{
    
    [self fetchRequestWithParam:param
                     requestUri:@"api/register"
                     httpMethod:BZPostRequest
                   hasSessionId:NO
                        success:success
                        failure:failure];

    
}


- (void)loginOutCurrentUserByHeaderParam:(NSDictionary *)headerParam
                                 Success:(void(^)(NSString *code , id responseObject))success
                                 failure:(void(^)(NSString *code,NSError *error))failure{
    
    [self fetchRequestWithParam:nil
                     requestUri:@"api/purview/logout"
                     httpMethod:BZPostRequest
                   hasSessionId:YES
                        success:^(NSString *code, id responseObject) {
                            
                            BZLog(@"code=%@---responseObject=%@",code,responseObject);
                            
                            NSError *error  = nil;
                            BOOL  isSuccess =  [BZDataBaseManager deleteDataBaseBySync:@"bzuc"
                                                                             tableName:@"uctable"
                                                                       sqlConditionStr:nil
                                                                              outError:&error];
                            
                            if (isSuccess) {
                                [BZUCCurrentUser shareInstance].userModel.password = @"";
                            }
                            if (success) {
                                success(code,responseObject);
                            }
                            
                            [[NSNotificationCenter defaultCenter]postNotificationName:BZLoginOut
                                                                               object:nil
                                                                             userInfo:nil];
                        } failure:^(NSString *code, NSError *error) {
                            
                            
                            
                        }];
    

}


- (BOOL)loginByUserNameSync:(NSString *)userName
               password:(NSString *)password
               outError:(NSError *__autoreleasing *)outError{


    if ([userName length] && [password length]) {
        
        NSString *psw = [password md5String];
        
        NSDictionary *param = @{@"username":userName,@"password":psw};
        
        __block BOOL success = NO;
        __block id response ;
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  
        
        [self fetchRequestWithParam:param
                         requestUri:@"api/logon"
                         httpMethod:BZPostRequest
                       hasSessionId:YES
                            success:^(NSString *code, id responseObject) {
                                
                                BZLog(@"code=%@---responseObject=%@",code,responseObject);
                                
                                NSError *error     = nil;
                                BZUCUserModel *user = [MTLJSONAdapter modelOfClass:[BZUCUserModel class]
                                                                fromJSONDictionary:responseObject
                                                                             error:&error];
                                if (user) {
                                    
                                    user.password = password;
                                    /*
                                    [BZDataBaseManager updateDataBaseByUserModelAsync:user
                                                                              success:nil
                                                                              failure:nil];*/
                                    //UCSDK
                                    BZUCUser *ucUser = [BZUCUser shareInstance];
                                    [ucUser clean];
                                    ucUser.customerId = user.customerId;
                                    ucUser.username = user.username;
                                    ucUser.nickname = user.nickname;
                                    ucUser.realName = user.realName;
                                    ucUser.phone = user.phone;
                                    ucUser.portrait = user.portrait;
                                    ucUser.type = user.type;
                                    ucUser.sectName = user.sectName;
                                    ucUser.status = user.status;
                                    ucUser.sectId = user.sectId;
                                    ucUser.password = user.password;
                                    ucUser.sessionId = user.sessionId;
                                    ucUser.backgroundUrl = user.backgroundUrl;
                                    ucUser.expireTime = user.expireTime;
                                    ucUser.isHeadlineFirst = user.isHeadlineFirst;
                                    //更新数据库
                                    [BZUCDataBaseManager updateUserAsync:ucUser success:nil failure:nil];
                                }
                                success = YES;
                                response = responseObject;
                                
                                dispatch_semaphore_signal(semaphore);

                                
                            } failure:^(NSString *code, NSError *error) {
                                
                                
                                //[ZZFDataBaseManager deleteDataBaseLoginUserlSync];
                                [BZUCDataBaseManager deleteLoginUserlSync];
                                
                                success = NO;
                                
                                if (*outError) {
                                    
                                    *outError = error;
                                }
                                dispatch_semaphore_signal(semaphore);
                            }];

               return success;
    }
    return NO;
}



- (void)loginByUserName:(NSString *)userName
               password:(NSString *)password
             success:(void(^)(NSString *code , id responseObject))success
             failure:(void(^)(NSString *code,NSError *error))failure{
    
    if ([userName length] && [password length]) {
        
        NSString *psw = [password md5String];

        NSDictionary *param = @{@"username":userName,@"password":psw};
        
        [self fetchRequestWithParam:param
                         requestUri:@"api/logon"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:^(NSString *code, id responseObject) {
                                
                                
                                BZLog(@"code=%@---responseObject=%@",code,responseObject);
                                
                                NSError *error     = nil;
                                BZUCUserModel *user = [MTLJSONAdapter modelOfClass:[BZUCUserModel class]
                                                               fromJSONDictionary:responseObject
                                                                            error:&error];
                                if (user) {
                                    
                                    user.password = password;
                                    
                                    //UCSDK
                                    BZUCUser *ucUser = [BZUCUser shareInstance];
                                    [ucUser clean];
                                    ucUser.customerId = user.customerId;
                                    ucUser.username = user.username;
                                    ucUser.nickname = user.nickname;
                                    ucUser.realName = user.realName;
                                    ucUser.phone = user.phone;
                                    ucUser.portrait = user.portrait;
                                    ucUser.type = user.type;
                                    ucUser.sectName = user.sectName;
                                    ucUser.status = user.status;
                                    ucUser.sectId = user.sectId;
                                    ucUser.password = user.password;
                                    ucUser.sessionId = user.sessionId;
                                    ucUser.backgroundUrl = user.backgroundUrl;
                                    ucUser.expireTime = user.expireTime;
                                    ucUser.isHeadlineFirst = user.isHeadlineFirst;
                                    //更新数据库
                                    [BZUCDataBaseManager updateUserAsync:ucUser success:nil failure:nil];
                                    
                                    BZDbUserTable *userTable = [[BZDbUserTable alloc]init];

                                    
                                    [BZDataBaseManager updateDataBaseByModelAsync:user
                                                                           dbName:@"bzuc"
                                                                        tableName:@"uctable"
                                                                     conditionSql:nil
                                                                          success:^(BOOL bSucced) {
                                        
                                    } failure:^(NSError *error) {
                                        
                                    }];
                                }
                                if (success) {
                                    success(code,responseObject);
                                }
                                
                                [[NSNotificationCenter defaultCenter]postNotificationName:BZLoginSuccess
                                                                                   object:nil
                                                                                 userInfo:@{@"response":responseObject}];

                                
                            } failure:^(NSString *code, NSError *error) {
                                
                                
                                //[ZZFDataBaseManager deleteDataBaseLoginUserlSync];
                                [BZUCDataBaseManager deleteLoginUserlSync];
                                
                                if (failure){
                                    failure(code,error);
                                }
                                
                            }];
        
    }
    
}


- (void)checkoutUserName:(NSString *)userName
                 success:(void(^)(NSString *code , id responseObject))success
                 failure:(void(^)(NSString *code,NSError *error))failure{
    
    if ([userName length]) {
        
        NSDictionary *param = @{@"username":userName};
        
        
        [self fetchRequestWithParam:param requestUri:@"api/forgot/username-check" httpMethod:BZPostRequest hasSessionId:NO success:success failure:failure];
        
    }

}

- (void)findSMSCodeOfPhone:(NSString *)phoneNum withImei:(NSString*)imei withCode:(NSInteger) type
                   success:(void(^)(NSString *code , id responseObject))success
                   failure:(void(^)(NSString *code,NSError *error))failure{

    
    if ([phoneNum length]) {
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];  //@{@"phone":phoneNum};
        
        param[@"phone"] = phoneNum;
        param[@"imei"] = imei;
        param[@"code"]  = @(type);

        [self fetchRequestWithParam:param
                         requestUri:@"api/forgot/phone-code"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];
    }

}



- (void)checkSMSCodeOfPhone:(NSString *)phoneNum
                    smsCode:(NSString *)smsCode
                   success:(void(^)(NSString *code , id responseObject))success
                   failure:(void(^)(NSString *code,NSError *error))failure{
    
    
    if ([phoneNum length] && [smsCode length]) {
        
        NSDictionary *param = @{@"phone":phoneNum,@"code":smsCode};
        [self fetchRequestWithParam:param
                         requestUri:@"api/forgot/check-code"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];
    }
    
}


- (void)resetPasswordWithNewPassword:(NSString *)newPassword
                               phone:(NSString *)phone
                             success:(void(^)(NSString *code , id responseObject))success
                             failure:(void(^)(NSString *code,NSError *error))failure{
    
    
    if ([newPassword length] && [phone length]) {
        
        NSDictionary *param = @{@"password":newPassword,@"phone":phone};
        [self fetchRequestWithParam:param
                         requestUri:@"api/forgot/rest-password"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];

//        [self requestByParam:param uri:@"api/forgot/rest-password" success:success failure:failure];
    }
}



- (void)editPasswordWithNewPassword:(NSString *)newPassword
                        oldPassword:(NSString *)oldPassword
                            success:(void(^)(NSString *code , id responseObject))success
                            failure:(void(^)(NSString *code,NSError *error))failure{
    
    
    if ([newPassword length] && [oldPassword length]) {
        
        NSDictionary *param = @{@"password":newPassword,@"pwd":oldPassword};
        
        [self fetchRequestWithParam:param
                         requestUri:@"api/purview/user/edit-password"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];
//        [self requestByParam:param uri:@"api/purview/user/edit-password" success:success failure:failure];
    }
}

- (void)findAccountCodeOfPhone:(NSString *)phoneNum
                      withImei:(NSString*)imei
                      withCode:(NSInteger) type
                       success:(void(^)(NSString *code , id responseObject))success
                       failure:(void(^)(NSString *code , NSError *error))failure{
    
    if ([phoneNum length]) {
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];  //@{@"phone":phoneNum};
        
        param[@"phone"] = phoneNum;
        param[@"imei"] = imei;
        param[@"code"]  = @(type);
        
        [self fetchRequestWithParam:param
                         requestUri:@"api/purview/user/phone-code"
                         httpMethod:BZPostRequest
                       hasSessionId:NO
                            success:success
                            failure:failure];

    }
    
}

- (void)changeAccountWithPhone:(NSString *)phone
                      withCode:(NSString *)code
                  withPassword:(NSString *)pwd
                       success:(void(^)(NSString *code , id responseObject))success
                       failure:(void(^)(NSString *code , NSError *error))failure{

    NSDictionary *param = @{@"phone":phone,@"code":code,@"password":pwd};
    
    [self fetchRequestWithParam:param
                     requestUri:@"api/purview/user/edit-phone"
                     httpMethod:BZPostRequest
                   hasSessionId:NO
                        success:success
                        failure:failure];
}

@end
